<?php
class Mozg_Response_Http extends Mozg_Response
{
    private $_headers = array();
    private $_headersRaw = array();
    private $_isRedirect = false;
    private $_httpResponseCode = 200;
    private $_isCompress = false;
    private $_isCompressed = false;

    public function __construct ()
    {
        parent::__construct();
        if (Mozg_Cfg::Get('global')->GetIsCompress()) {
            $this->TurnCompression(true);
        }
    }
    
    /**
     * Set a header
     *
     * If $replace is true, replaces any headers already defined with that
     * $name.
     *
     * @param string $name
     * @param string $value
     * @param boolean $replace
     * @return Zend_Controller_Response_Abstract
     */
    public function setHeader ($name, $value, $replace = false)
    {
        $this->canSendHeaders(true);
        $name = (string) $name;
        $value = (string) $value;
        if ($replace) {
            foreach ($this->_headers as $key => $header) {
                if ($name == $header['name']) {
                    unset($this->_headers[$key]);
                }
            }
        }
        $this->_headers[] = array('name' => $name , 'value' => $value , 'replace' => $replace);
        return $this;
    }
    
    /**
     * Set redirect URL
     *
     * Sets Location header and response code. Forces replacement of any prior
     * redirects.
     *
     * @param string $url
     * @param int $code
     * @return Zend_Controller_Response_Abstract
     */
    public function setRedirect ($url, $code = 302)
    {
        $this->canSendHeaders(true);
        $this->setHeader('Location', $url, true)->setHttpResponseCode($code);
        return $this;
    }
    
    /**
     * Is this a redirect?
     *
     * @return boolean
     */
    public function isRedirect ()
    {
        return $this->_isRedirect;
    }
    
    /**
     * Return array of headers; see {@link $_headers} for format
     *
     * @return array
     */
    public function getHeaders ()
    {
        return $this->_headers;
    }
    
    /**
     * Clear headers
     *
     * @return Zend_Controller_Response_Abstract
     */
    public function clearHeaders ()
    {
        $this->_headers = array();
        return $this;
    }
    
    /**
     * Set raw HTTP header
     *
     * Allows setting non key => value headers, such as status codes
     *
     * @param string $value
     * @return Zend_Controller_Response_Abstract
     */
    public function setRawHeader ($value)
    {
        $this->canSendHeaders(true);
        if ('Location' == substr($value, 0, 8)) {
            $this->_isRedirect = true;
        }
        $this->_headersRaw[] = (string) $value;
        return $this;
    }
    
    /**
     * Retrieve all {@link setRawHeader() raw HTTP headers}
     *
     * @return array
     */
    public function getRawHeaders ()
    {
        return $this->_headersRaw;
    }
    
    /**
     * Clear all {@link setRawHeader() raw HTTP headers}
     *
     * @return Zend_Controller_Response_Abstract
     */
    public function clearRawHeaders ()
    {
        $this->_headersRaw = array();
        return $this;
    }
    
    /**
     * Clear all headers, normal and raw
     *
     * @return Zend_Controller_Response_Abstract
     */
    public function clearAllHeaders ()
    {
        return $this->clearHeaders()->clearRawHeaders();
    }
    
    /**
     * Set HTTP response code to use with headers
     *
     * @param int $code
     * @return Zend_Controller_Response_Abstract
     */
    public function setHttpResponseCode ($code)
    {
        if (! is_int($code) || (100 > $code) || (599 < $code)) {
            throw new Mozg_Exception_System('Invalid HTTP response code');
        }
        if ((300 <= $code) && (307 >= $code)) {
            $this->_isRedirect = true;
        } else {
            $this->_isRedirect = false;
        }
        $this->_httpResponseCode = $code;
        return $this;
    }
    
    /**
     * Retrieve HTTP response code
     *
     * @return int
     */
    public function getHttpResponseCode ()
    {
        return $this->_httpResponseCode;
    }
    
    /**
     * Can we send headers?
     *
     * @param boolean $throw Whether or not to throw an exception if headers have been sent; defaults to false
     * @return boolean
     * @throws Zend_Controller_Response_Exception
     */
    public function canSendHeaders ($throw = false)
    {
        $ok = headers_sent($file, $line);
        if ($ok && $throw) {
            throw new Mozg_Exception_System('Cannot send headers; headers already sent in ' . $file . ', line ' . $line);
        }
        return ! $ok;
    }
    
    /**
     * Send all headers
     *
     * Sends any headers specified. If an {@link setHttpResponseCode() HTTP response code}
     * has been specified, it is sent with the first header.
     *
     * @return Zend_Controller_Response_Abstract
     */
    public function sendHeaders ()
    {
        // Only check if we can send headers if we have headers to send
        if (count($this->_headersRaw) || count($this->_headers) || (200 != $this->_httpResponseCode)) {
            $this->canSendHeaders(true);
        } elseif (200 == $this->_httpResponseCode) {
            // Haven't changed the response code, and we have no headers
            return $this;
        }
        $httpCodeSent = false;
        foreach ($this->_headersRaw as $header) {
            if (! $httpCodeSent && $this->_httpResponseCode) {
                header($header, true, $this->_httpResponseCode);
                $httpCodeSent = true;
            } else {
                header($header);
            }
        }
        foreach ($this->_headers as $header) {
            if (! $httpCodeSent && $this->_httpResponseCode) {
                header($header['name'] . ': ' . $header['value'], $header['replace'], $this->_httpResponseCode);
                $httpCodeSent = true;
            } else {
                header($header['name'] . ': ' . $header['value'], $header['replace']);
            }
        }
        if (! $httpCodeSent) {
            header('HTTP/1.1 ' . $this->_httpResponseCode);
            $httpCodeSent = true;
        }
        return $this;
    }
    
    public function TurnCompression ($switch)
    {
        $this->_isCompress = (bool) $switch;
    }
    
    public function IsCompressionEnabled ()
    {
        return $this->_isCompress && $this->IsCompressionSupported();
    }
    
    public function IsCompressionSupported()
    {
        return strstr(getenv("HTTP_ACCEPT_ENCODING"), "gzip") !== false;
    }
    
    protected function Compress()
    {
        if ($this->_isCompressed) return true;
        $this->_isCompressed = true;
        
        $content = $this->GetBody();
        $content = gzencode($content, 7);

        $this->SetHeader('Content-Encoding', 'gzip');
        $this->SetHeader('Content-Length', strlen($content));

        $this->SetBody($content);

        return true;
    }

    public function GetResponse()
    {
    	$this->RunOutputFilters();
    	if ($this->IsCompressionEnabled())
    	{
    		$this->Compress();
    	}

    	return $this->GetBody();
    }
    
    public function SendResponse()
    {
    	$content = $this->GetResponse();
    	$this->sendHeaders();
		echo $content;
    }
}